﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Shake.Business.Infrastructures;
using Shake.Domain.Models;
using Shake.Framework.Repository;

namespace Shake.Business.Services
{
    public class QualificationService : IQualificationService
    {
        public IRepository _repository { get; set; }
        public Qualification GetEntity(string id)
        {
            using (var factory = _repository.CreateSessionFactory())
            {
                var session = factory.GetCurrentSession();
                var query = session.QueryOver<Qualification>();

                var entity = query.Where(t => t.Id == id).List();
                if (entity.Count == null) return null;
                return entity.FirstOrDefault();
            }
        }
        public void Save(Qualification entity)
        {
            if (entity == null) throw new Exception("参数异常");
            if (string.IsNullOrEmpty(entity.Id))
            {
                entity.Id = Guid.NewGuid().ToString("N");                
                _repository.Insert(entity);
            }
            else
            {
                var oEntity = GetEntity(entity.Id);
                oEntity.QualName = entity.QualName;
                oEntity.QualType = entity.QualType;
                oEntity.QualLevel = entity.QualLevel;
                oEntity.ValidStartDate = entity.ValidStartDate;
                oEntity.ValidEndDate = entity.ValidEndDate;
                oEntity.Remark = entity.Remark;
                oEntity.UserId = entity.UserId;
                _repository.Update(oEntity);
            }
        }

        public void Remove(List<Qualification> entitys)
        {
            if (entitys == null) return;
            _repository.DeleteMany(entitys);
        }

        public List<Qualification> GetAll()
        {
            using (var factory = _repository.CreateSessionFactory())
            {
                var session = factory.GetCurrentSession();
                var query = session.QueryOver<Qualification>();
                var results = query.List();
                return results.ToList();
            }
        }
        public List<Qualification> GetByUserId(string userId)
        {
            using (var factory = _repository.CreateSessionFactory())
            {
                var session = factory.GetCurrentSession();
                var query = session.QueryOver<Qualification>().Where(p => p.UserId == userId);
                var results = query.List();
                return results.ToList();
            }
        }
    }
}
